//
//  HJMineVC.m
//  project
//
//  Created by hu on 2019/3/21.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJMineVC.h"
#import "YFProfileView.h"
#import "YFMobManager.h"
#import "HJAuthVC.h"
#import "HJSettingVC.h"
#import "UINavigationBar+YFExtension.h"
#import "YFAlert.h"
#import "YFEditProfileVC.h"
#import "LEEAlert.h"
#import "HJOtherDynamic.h"
#import "HJFansVC.h" // 粉丝和关注数

// tableView头部高度
#define  tableViewHeaderHeight (IS_FULL_SCREEN ? 53 * SCREEN_WIDTH / 75 + 44 : 53 * SCREEN_WIDTH / 75)+75

@interface HJMineVC ()<SDCycleScrollViewDelegate>
/**
 头部
 */
@property (nonatomic, strong) YFProfileView *profileView;

/**
 类别View
 */
@property (nonatomic,strong) UIView * categaryView;


@property (nonatomic,strong) UILabel * fansNum;
@property (nonatomic,strong) UILabel * attenNum;
/**
 粉丝
 */
@property (nonatomic,strong) UILabel * fansLabel;

/**
 关注
 */
@property (nonatomic,strong) UILabel * attenLabel;
@property (nonatomic,strong) UIButton * fansBtn;
@property (nonatomic,strong) UIButton * attBtn;

/**
 轮播
 */
@property (nonatomic,strong) SDCycleScrollView *cycleScrollView;

/**
 广告数组
 */
@property (nonatomic,strong) NSArray * advertArray;

/**
 cell 数组数据
 */
@property (nonatomic,strong) NSMutableArray <HJMineModel *>* titleArray;



@end

@implementation HJMineVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:UIImage.new forBarMetrics:(UIBarMetricsDefault)];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:UIColor.whiteColor.image forBarMetrics:(UIBarMetricsDefault)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"";
    self.rightNavTitle = @"设置";
    [self requestAdvert];
    [mNotificationCenter addObserver:self selector:@selector(update:) name:@"updateUINotification" object:nil];
   
}

- (void)didClickRightNavAction {
    [self.navigationController pushViewController:HJSettingVC.new animated:YES];
}

-(void)update:(NSNotification *)notification {
    [self.profileView updateViews];
    // 顺便修改一下融云的用户头像
//    HJUserModel *model = [HJUserManager getUserModel];
//    RCUserInfo * currentInfo = [[RCUserInfo alloc]initWithUserId:model.userId name:model.nickName portrait:model.avatar];
//    [RCIMClient sharedRCIMClient].currentUserInfo = currentInfo;
}
- (void)configTableView {
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.frame = CGRectMake(0, -NAVIGATION_BAR_HEIGHT, self.view.width, self.view.height - Height_TabBar);
    self.tableView.emptyViewOffset = 100;
    
    UIView * header = [UIView new];
    [header addSubview:self.profileView];
    [header addSubview:self.categaryView];
    
    [self.fansNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.categaryView).offset(12);
        make.left.equalTo(self.categaryView).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 20));
    }];
    [self.fansLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.fansNum.mas_bottom).offset(10);
        make.left.equalTo(self.categaryView).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 20));
    }];
    [self.fansBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.categaryView).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 75));
    }];
    
    [self.attenNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.fansNum);
        make.left.equalTo(self.fansNum.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 20));
    }];
    [self.attenLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.fansLabel);
        make.left.equalTo(self.fansLabel.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 20));
    }];
    [self.attBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.fansBtn);
        make.left.equalTo(self.fansBtn.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH/2, 20));
    }];
    
    self.tableView.tableHeaderView = header;
    self.tableView.tableHeaderView.height = tableViewHeaderHeight;
    
    self.view.backgroundColor = [UIColor withHex:0xe6e6e6];
    self.tableView.backgroundColor = [UIColor withHex:0xe6e6e6];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    [self.tableView registerCellByClassName:@"UITableViewCell"];
    self.tableView.showsVerticalScrollIndicator = YES;
    @weakify(self)
    self.tableView.fullScreenRefresh(^{
        @strongify(self)
        [self loadData];
    });
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.profileView.height+75) {
        self.navTitle = @"我的";
        self.navigationItem.rightBarButtonItem.tintColor = UIColor.blackColor;
    } else {
        self.navigationItem.rightBarButtonItem.tintColor = UIColor.whiteColor;
        self.navTitle = @"";
    }
    [self.navigationController.navigationBar gradientBackground:UIColor.whiteColor textColor:UIColor.blackColor offsetY:scrollView.contentOffset.y critical:self.profileView.height+75];
}

-(NSMutableArray<HJMineModel *> *)titleArray {
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

#pragma mark - UITableViewDataSource UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * identifier = @"UITableViewCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont fontWithName:PingFangSC_Medium size:18];
    if (self.titleArray[indexPath.row].cellID.intValue == 2) {
        self.titleArray[indexPath.row].icon = @"Invitation";
    }
    cell.imageView.image = [UIImage imageNamed:self.titleArray[indexPath.row].icon];
    cell.textLabel.text = self.titleArray[indexPath.row].name;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([[self classArray][indexPath.row] isEqualToString:@""] && self.titleArray[indexPath.row].url.length>0) {
        HJWebViewController * webVC = [HJWebViewController new];
        webVC.URLString = self.titleArray[indexPath.row].url;//@"http://192.168.1.63/src/test.html";
        webVC.navTitle = self.titleArray[indexPath.row].name;
        webVC.isBridge = YES;
        [self.navigationController pushViewController:webVC animated:YES];
        return;
    }
    [self ClasFrom:[self classArray][indexPath.row]];
}

-(NSArray *)classArray {
    NSArray * arr = @[@"HJMyDynamicVC",@"HJMyLikeVC",@""];
    return arr;
}

#pragma mark - 网络请求
- (void)loadData {
    NSString * url = [Api stringByAppendingString:personalCenterApi];
    @weakify(self)
    [HJHttpTool get:url params:nil success:^(HJResponeds *result) {
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary * dic = result.data;
            if ([dic.allKeys containsObject:@"myConcernAmount"]) {
                self.fansNum.text = [NSString stringWithFormat:@"%@",dic[@"othersConcernAmount"]];
                self.attenNum.text = [NSString stringWithFormat:@"%@",dic[@"myConcernAmount"]];
            }
            NSArray <HJMineModel *>*moduleList;
            [self.titleArray removeAllObjects];
            if ([dic.allKeys containsObject:@"moduleList"]) {
                moduleList = [NSArray yy_modelArrayWithClass:HJMineModel.class json:dic[@"moduleList"]];
            }
            for (int i=0; i<moduleList.count+2; i++) {
                HJMineModel * model = [[HJMineModel alloc]init];
                if (i==0) {
                    model.name = @"我的动态";
                    model.cellID = @"0";
                    model.icon = @"dongtai_mine";
                }else if (i==1) {
                    model.name = @"我点的赞";
                    model.cellID = @"1";
                    model.icon = @"zan_mine";
                }else {
                    model = moduleList[i-2];
                }
                [self.titleArray addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView endRefresh];
        });
    } failure:^(id result) {
        @strongify(self)
        [YFHud showError:result];
        [self.tableView endRefresh];
    }];
}

#pragma mark -- 加载广告
-(void)requestAdvert {
    @weakify(self)
    NSString * adertUrl = [Api stringByAppendingString:AdvertApi];
    [HJHttpTool get:adertUrl params:nil success:^(HJResponeds *result) {
        @strongify(self)
        [self requestShuffingCompleted:result.data];
    } failure:^(id result) {
        [YFHud showError:result];
    }];
}

#pragma mark - Lazy Load
- (YFProfileView *)profileView {
    if (!_profileView) {
        _profileView = [YFProfileView loadFromXib:YFProfileView.class];
        CGFloat height = IS_FULL_SCREEN ? 53 * SCREEN_WIDTH / 75 + 44 : 53 * SCREEN_WIDTH / 75;
        _profileView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
        @weakify(self)
        _profileView.avatarClickAction = ^{
            @strongify(self)
            [self.navigationController pushViewController:YFEditProfileVC.new animated:YES];
        };
        _profileView.changeBackgroundImageBlock = ^{
            @strongify(self)
            [LEEAlert actionsheet].config
            .LeeContent(@"更换相册封面")
            .LeeAddAction(^(LEEAction * _Nonnull action) {
                @weakify(self)
                action.title = @"从手机相册选择";
                action.titleColor = [UIColor blackColor];
                action.font = [UIFont systemFontOFSize14];
                action.clickBlock = ^{
                    [TZImagePickerTool selectImageFrom:self complete:^(UIImage *img) {
                        @strongify(self)
                        [self uploadBackgroundImageWithImg:img];
                    } isCamera:NO];
                };
            })
            .LeeAddAction(^(LEEAction * _Nonnull action) {
                action.title = @"拍摄";
                action.titleColor = [UIColor blackColor];
                action.font = [UIFont systemFontOFSize14];
                @weakify(self)
                action.clickBlock = ^{
                    [TZImagePickerTool selectImageFrom:self complete:^(UIImage *img) {
                        @strongify(self)
                        [self uploadBackgroundImageWithImg:img];
                    } isCamera:YES];
                };
            })
            .LeeAddAction(^(LEEAction * _Nonnull action) {
                action.type = LEEActionTypeCancel;
                action.title = @"取消";
                action.titleColor = [UIColor grayColor];
                action.font = [UIFont systemFontOFSize14];
            })
            .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
            .LeeShow();
        };
    }
    return _profileView;
}

-(UIView *)categaryView {
    if (!_categaryView) {
        _categaryView = [UIView new];
        _categaryView.frame = CGRectMake(0, CGRectGetMaxY(self.profileView.frame), SCREEN_WIDTH, 75);
        _categaryView.backgroundColor = [UIColor whiteColor];
        
        _fansNum = [self setupLabel];
        _fansLabel = [self setlabelWithTitle:@"粉丝"];
        _fansBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        @weakify(self)
        [[_fansBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self pushFansAndAttentionVCWithControl:FansVC];
        }];;
        [_categaryView addSubview:_fansNum];
        [_categaryView addSubview:_fansLabel];
        [_categaryView addSubview:_fansBtn];
        
        UIView * line = [UIView new];
        line.backgroundColor = [UIColor colorWithHex:0xE6E6E6];
        line.frame =CGRectMake(SCREEN_WIDTH/2-0.5, 17.5, 1, 35);
        [_categaryView addSubview:line];
        
        _attenNum = [self setupLabel];
        _attenLabel = [self setlabelWithTitle:@"关注"];
        _attBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [[_attBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self pushFansAndAttentionVCWithControl:AttenVC];
        }];;
        [_categaryView addSubview:_attenNum];
        [_categaryView addSubview:_attenLabel];
        [_categaryView addSubview:_attBtn];
        
        UIView * section = [UIView new];
        section.backgroundColor = [UIColor colorWithHex:0xE6E6E6];
        section.frame = CGRectMake(0, 65, SCREEN_WIDTH, 10);
        [_categaryView addSubview:section];
    }
    return _categaryView;
}

#pragma mark --push到粉丝和关注列表界面
-(void)pushFansAndAttentionVCWithControl:(controller)control {
    HJFansVC * fansVC = [HJFansVC new];
    fansVC.contro = control;
    [self.navigationController pushViewController:fansVC animated:YES];
}

-(UILabel *)setupLabel {
    UILabel * label = [UILabel new];
    label.textColor = [UIColor colorWithHex:0x292929];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"0";
    label.font = [UIFont fontWithName:PingFangSC_Medium size:20];
    return label;
}

-(UILabel *)setlabelWithTitle:(NSString *)title {
    UILabel * label = [UILabel new];
    label.textColor = [UIColor colorWithHex:0x808080];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOFSize15];
    label.text = title;
    
    return label;
}

#pragma mark -- banner
-(SDCycleScrollView *)cycleScrollView {
    if (!_cycleScrollView) {
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, tableViewHeaderHeight, SCREEN_WIDTH, 108) delegate:self placeholderImage:placeHolderImage];
        cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
        cycleScrollView.currentPageDotColor = [UIColor blackColor];
        cycleScrollView.delegate = self;
        cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        self.cycleScrollView = cycleScrollView;
        
        UIView * header = [UIView new];
        [header addSubview:self.profileView];
        [header addSubview:self.categaryView];
        [header addSubview:_cycleScrollView];
        self.tableView.tableHeaderView = header;
        self.tableView.tableHeaderView.height = tableViewHeaderHeight+108;
    }
    return _cycleScrollView;
}

-(void)requestShuffingCompleted:(NSArray *)model {
    NSMutableArray *imagesURLStrings = [NSMutableArray array];
    for(int i=0; i<model.count; i++) {
        NSDictionary * dic = model[i];
        [imagesURLStrings addObject:dic[@"icon"]];
    }
    if (imagesURLStrings.count==0) return;
    self.advertArray = [NSArray arrayWithArray:model];
    self.cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    [self.tableView reloadData];
}

#pragma mark --SDCycleScrollViewDelegate
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (self.advertArray.count>0) {
        NSDictionary * dic = self.advertArray[index];
        NSString *url = [NSString stringWithFormat:@"%@",dic[@"url"]];
        if ([url isEqual:NSNull.class] || [url isEqualToString:@"<null>"]) return;
        HJWebViewController * webVC = [HJWebViewController new];
        webVC.URLString = url;
        webVC.navTitle = [NSString stringWithFormat:@"%@",dic[@"title"]];
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

#pragma mark -- 更换背景图片
-(void)uploadBackgroundImageWithImg:(UIImage *)img {
    @weakify(self)
    NSString * url = [Api stringByAppendingString:UploadImageApi];
    [HJHttpTool uploadImageWithUrl:url params:nil name:@"multipartFiles" imageArray:@[img] completion:^(NSArray *result, NSError *error) {
        @strongify(self)
        if (result && result.count >=1) {
            [HJUserManager updateUserModelWithParams:@{@"backgroundIcon":[NSString stringWithFormat:@"%@",result[0]]} success:^{
                [self.profileView updateViews];
            }];
        }
    }];
}


@end



@implementation HJMineModel

-(NSString *)description {
    return [self yy_modelDescription];
}
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper {
    return @{@"cellID":@"id"};
}


@end
